<template>
  <div v-if="!openDetails"
    class="app-container flex flex-sub"
    style="background: none; height: 100%; padding: 1rem">
    <div class="flex"
      style="width: 340px; height: 100%">
      <el-card shadow="never"
        class="box-card flex-sub"
        style="overflow: auto">
        <div class="flex"
          style="margin-bottom: 1rem; justify-content: space-between">
          <el-button size="small"
            @click="toExpandAll('是')">
            <i class="el-icon-plus"
              style="color: #606266" />
            <span style="color: #606266">全部展开</span>
          </el-button>

          <el-button size="small"
            @click="toExpandAll('否')">
            <i class="el-icon-minus"
              style="color: #606266" />
            <span style="color: #606266">全部收起</span>
          </el-button>
        </div>

        <div style="border: 1px solid #c8c8c8; padding: 0.7rem; margin-top: 1rem">
          <div style="margin-right: 0px; overflow: auto"
            :style="{ height: treeHeight }"
            class="box-card">
            <el-tree ref="refTree"
              :data="tree"
              node-key="id"
              accordion
              :highlight-current="highlightCurrent"
              :expand-on-click-node="expandOnClickNode"
              :default-expand-all="expandAll"
              @node-click="nodeClick">
              <span class="custom-tree-node"
                slot-scope="{ node, data }">
                <span>
                  <el-radio v-model="selectedGrid"
                    :label="data.id"
                    @input="onInput">{{ node.label }}</el-radio></span>
              </span>
            </el-tree>
          </div>
        </div>
      </el-card>
    </div>
    <div class="flex flex-sub"
      style="margin-left: 1rem; width: calc(100% - 350px)">
      <el-card shadow="never"
        class="box-card flex-sub"
        style="overflow: auto">
        <div class="div-query">
          <div class="collapse">
            <div class="collapse-header"
              @click="panelActive = !panelActive">
              <i class="collapse-header-icon"
                :class="[
                  panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top',
                ]" />
              {{ panelActive ? "隐藏" : "展开" }}查询条件
            </div>
            <div class="collapse-content">
              <el-collapse-transition>
                <div v-show="panelActive">
                  <el-form size="small"
                    label-position="right">
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="设备名称"
                          label-width="80px">
                          <el-input v-model="searchModel.deviceName"
                            placeholder="设备名称"
                            clearable
                            class="filter-item search-item" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="设备编号"
                          label-width="80px">
                          <el-input v-model="searchModel.deviceCode"
                            placeholder="设备编号"
                            clearable
                            class="filter-item search-item" />
                        </el-form-item>
                      </el-col>

                      <el-col :span="8">
                        <el-form-item style="margin-left: 10px">
                          <el-button type="primary"
                            icon="el-icon-search"
                            @click="toSearch"
                            style="margin-right: 10px">搜索</el-button>
                          <el-button type="info"
                            @click="toReset"
                            style="margin-right: 10px">
                            <i class="el-icon-delete" />
                            重置
                          </el-button>

                          <el-button size="small"
                            @click="getDataList">
                            <i class="el-icon-refresh"
                              style="color: #606266" />
                            <span style="color: #606266">刷新</span>
                          </el-button>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </el-collapse-transition>
            </div>
          </div>
        </div>
        <!-- 卡片区域 -->
        <div class="view box-card"
          :style="{ height: `${viewHeight}px` }">
          <div class="view-item"
            v-for="(item, index) in dataList"
            :key="index">
            <div class="flex align-center">
              <span class="flex-sub"
                style="font-size: 18px; font-family: SourceHanSans">{{ item.deviceName }}</span>
              <span class="flex"
                style="justify-content: end;width:100px">
                <el-tag size="small"
                  :style="
                    item.deviceRunningState
                    | constantKeyTagStyleObj('DEVICE_RUNNING_STATE')
                  "
                  style="display: flex; align-items: center">
                  <span class="status-circle"
                    :style="{
                      background:
                        deviceRunningStateStr[item.deviceRunningState],
                    }" />
                  {{
                    item.deviceRunningState
                    | constantKeyValue("DEVICE_RUNNING_STATE")
                  }}
                </el-tag>
              </span>
            </div>
            <div class="flex align-center"
              style="margin: 5px 0">
              <span class="flex-sub"
                style="font-size: 12px">编号：{{ item.deviceCode }}</span>
              <span class="flex flex-sub align-center"
                style="justify-content: end">
                当前功率：<span
                  style="color: #ffa167; font-size: 18px">{{ item.power }}W</span>
              </span>
            </div>
            <div style="width: 100%;height: 150px; ">
              <!-- echart -->
              <!-- <div :id="'key' + index" style="height: 100%" /> -->
              <chart-template :chart-option="use_power_option(item.curveList)"
                v-if="item.curveList && item.curveList.length != 0" />
            </div>
            <div class="flex align-center"
              style="position: absolute;bottom: 5px;width: 98%;">
              <span style="width: 220px">
                更新时间：{{ updateDate | datefmt("YYYY-MM-DD HH:mm") }}
              </span>
              <span class="flex flex-sub check-detail"
                style="justify-content: end">
                <el-button type="primary"
                  size="small"
                  @click="toDetail(item)">
                  查看详情
                  <i class="el-icon-arrow-right el-icon--right" />
                </el-button>
              </span>
            </div>
          </div>
          <div v-if="dataList.length == 0"
            class="w-full flex justify-center align-center">
            <div class="flex-1  flex justify-center"
              style="font-size:20px">无数据。</div>
          </div>
        </div>
        <div>
          <pagination v-show="total > 0"
            :total="total"
            :page.sync="pagination.pageNum"
            :limit.sync="pagination.pageSize"
            :page-sizes="pageSizeOptions"
            @pagination="getDataList" />
        </div>
      </el-card>
    </div>
  </div>
  <Detail v-else
    :detailsData="detailsData"
    @exitDetail="exitDetail()" />
</template>
<script>
import dataTableMixins from "@/mixins/data-table-mixins";
import Pagination from "@/components/Pagination";
import GridManageApi from "@/api/grid-manage";
import dataMonitorApi from "@/api/data-monitor";
import ChartTemplate from "@/components/Chart/ChartTemplate"; //导入图表模板
import { use_power_option } from "./chartOption";
import Detail from "./components/Detail.vue";

export default {
  components: {
    Pagination,
    ChartTemplate,
    Detail,
  },
  mixins: [dataTableMixins],
  data () {
    return {
      use_power_option: use_power_option,
      treeHeight: "0px",
      viewHeight: 0,
      tree: [],

      expandOnClickNode: false,
      expandAll: false,
      highlightCurrent: true,
      showRightMenu: false,

      selectedGrid: "",
      updateDate: new Date(),
      /** 用电详情 */
      openDetails: false,
      /** 详情数据 */
      detailsData: {
        info: {},
        data: [],
      },
      deviceRunningStateStr: {
        报警: "#F44343",
        故障: "rgb(237 138 76)",
        正常: "#40E361",
        启动: "#2A7BFF",
        离线: "#ABB1B9",
        隔离: "rgb(104 106 108)",
        反馈: "#13c2c2",
      },
    };
  },
  mounted () {
    this.getHeightAndWidth();
    this.getTree();
    this.getDataList();
  },
  methods: {
    getHeightAndWidth () {
      let clientHeight = 0;
      if (
        document.body.scrollHeight === window.screen.height &&
        document.body.scrollWidth === window.screen.width
      ) {
        clientHeight = window.screen.height - 5; // 网页可见区域高
      } else {
        clientHeight = document.body.clientHeight - 5; // 网页可见区域高
      }
      this.viewHeight = clientHeight - 340;
      this.treeHeight = clientHeight - 250 + "px";
    },

    getTree () {
      GridManageApi.getGridTree()
        .then((res) => {
          this.tree = res.data.data.rows;
        })
        .catch(() => {
          this.tree = [];
        });
    },

    toExpandAll (text) {
      if (text === "是") {
        this.expandAll = true;
      } else {
        this.expandAll = false;
      }
      for (var i = 0; i < this.$refs.refTree.store._getAllNodes().length; i++) {
        this.$refs.refTree.store._getAllNodes()[i].expanded = this.expandAll;
      }
    },

    nodeClick (data) {
      //   debugger;
    },

    onInput () {
      this.getDataList();
    },

    getDataList () {
      this.loading = true;
      const searchModel = this.formatSearchData(this.searchModel);
      // searchModel.gridMount = this.selectedGrid;
      searchModel.parentGuid = this.selectedGrid;
      searchModel.deviceType = 97;
      searchModel.isNeedEleData = true;
      dataMonitorApi
        .getEquipmentList({
          ...this.pagination,
          ...searchModel,
          ...this.sort,
        })
        .then((ret) => {
          this.dataList = ret.data.data.rows;

          this.total = ret.data.data.total;
          this.loading = false;

          this.updateDate = new Date();

          this.dataList.forEach((ele, i) => {
            if (ele.curveList && ele.curveList.length != 0) {
              this.updateChartOption(ele, i);
            }
          });
        })
        .catch(() => {
          this.loading = false;
          this.dataList = [];
          this.total = 0;
        });
    },
    toSearch () {
      this.pagination.pageNum = 1;
      this.getDataList();
    },
    toReset () {
      this.searchModel = {};
      this.sort = {};
      this.$refs.elTable.clearSort();
      this.$refs.elTable.clearFilter();
      this.toSearch();
    },

    updateChartOption (ele, i) {
      var legendData = [
        {
          name: "耗值",
          textStyle: {
            color: "#0063ED",
          },
          pageIconColor: "#0063ED",
          shadowColor: "rgba(41, 123, 239, 0.77)",
        },
      ];
      var xAxisData = {
        xAxis: [],
      };
      var yAxisData = {
        yAxis1: [],
      };
      ele.curveList.forEach((e) => {
        xAxisData.xAxis.push(e.time);
        yAxisData.yAxis1.push(e.energy);
      });

      var seriesData = [];
      legendData.forEach((ele, idx) => {
        var key = "yAxis" + (idx + 1);
        var itemData = yAxisData[key];

        seriesData.push({
          name: ele.name,
          type: "line",
          data: itemData,
          smooth: false,
          showSymbol: false,
          lineStyle: {
            width: 2,
            shadowColor: ele.shadowColor,
            shadowBlur: 10,
            shadowOffsetX: 3,
            shadowOffsetY: 5,
          },
          itemStyle: {
            color: ele.pageIconColor,
          },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: "rgba(42,123,255,0.45)" },
                { offset: 1, color: "rgba(42,123,255,0.00)" },
              ],
              globalCoord: true, // 缺省为 false
            },
          },
          label: {
            normal: {
              show: false,
              position: "top",
              color: ele.pageIconColor,
              distance: 2,
            },
          },
        });
      });

      var chartOption = {
        tooltip: {
          trigger: "axis",
          // axisPointer: {
          //   type: 'line',
          // },
        },
        toolbox: {
          feature: {
            saveAsImage: { show: false },
          },
          top: -10,
          right: 20,
        },
        grid: {
          left: "3%",
          right: "3%",
          bottom: "1%",
          top: "10%",
          containLabel: true,
        },
        legend: {
          left: "right",
          padding: [2, 10, 2, 10],
          data: legendData,
          itemHeight: 13,
          show: false,
        },
        xAxis: {
          type: "category",
          data: xAxisData.xAxis,
          boundaryGap: false,
          axisTick: {
            alignWithLabel: true,
          },
          axisLabel: {
            interval: 0,
            fontSize: 15,
            // rotate: '45'
          },
          show: false,
        },
        yAxis: [
          {
            type: "value",
            min: 0,

            max: "dataMax",
            position: "left",
            axisLine: {
              lineStyle: {
                color: "#999",
              },
              show: false,
            },
            axisLabel: {
              formatter: "{value}",
              show: false,
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                // color: "#E6E8EB",
              },
            },
            axisTick: {
              show: false,
            },
          },
        ],
        series: seriesData,
      };
      if (this.chartD) {
        this.chartD.dispose();
      }
      this.$nextTick(() => {
        const id = "key" + i;
        if (this.getChart(id)) {
          this.chartD = this.getChart(id);
          this.createChart(this.chartD, chartOption);
        }
      });
    },
    getChart (id) {
      if (document.getElementById(id)) {
        return echarts.init(document.getElementById(id));
      }
      return null;
    },

    createChart (charts, option) {
      // const charts = echarts.init(document.getElementById(createId))
      charts.setOption(option);
      window.addEventListener("resize", () => {
        charts.resize();
      });
    },
    /**
     * 查看详情
     * @param {*} item
     */
    toDetail (item) {
      this.detailsData.info = { ...item };
      const date = this.$moment(new Date()).format("YYYY-MM-DD");
      // 获取该用电详情
      dataMonitorApi
        .getDeviceRealTimeData({
          deviceCode: item.deviceCode,
          beginTime: date + ' ' + '00:00:00',
          endTime: date + ' ' + '23:59:59'
        })
        .then((res) => {
          if (res.status === 200) {
            this.detailsData.data = [...res.data];
            this.openDetails = true;
          }
        });
    },
    /**
     * 退出详情
     */
    exitDetail () {
      this.openDetails = false;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../../styles/part-custom";

.view {
  overflow: auto;
  display: flex;
  flex-wrap: wrap;

  .view-item {
    border: 1px solid #e6e8eb;
    height: 260px;
    border-radius: 2px;
    width: 32%;
    margin-right: 1%;
    margin-bottom: 1%;
    padding: 10px;
    color: #272c33;
    position: relative;
  }
}

.w-full {
  width: 100%;
}

.flex {
  display: flex;

}

.flex-1 {
  flex: 1;
}

.align-center {
  align-items: center;
}

.justify-center {
  justify-content: center;
}

.status-circle {
  width: 8px;
  height: 8px;
  border-radius: 319px;
  background: black;
  margin-right: 4px;
}

/deep/.el-radio__input.is-checked+.el-radio__label {
  color: #409eff;
  background-color: #77b8fd;
  color: #fff;
}

/deep/ .check-detail .el-button {
  padding: 7px;
}
</style>
